/* eslint-disable import/no-extraneous-dependencies */
import React, { useMemo, useState, useEffect } from 'react';
import { Button, Form, Input, Select, DatePicker, Col, Row, Tooltip, Table, Switch, Pagination, Tree, message, Modal, Checkbox, Upload, UploadFile, Dropdown, MenuProps } from 'antd';
import {
  SyncOutlined,
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  VerticalAlignBottomOutlined,
  ToTopOutlined,
  AppstoreFilled,
  DoubleRightOutlined,
  CheckCircleOutlined,
  UnlockOutlined,
  InboxOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import type { DataNode } from 'antd/es/tree';
import type { ColumnsType } from 'antd/es/table';
import { getUserListAPI, delUserAPI, deptTreeAPI, getPostRoleAPI, patchUserPwdAPI, getUserInfoAPI, putUserStatusAPI, uploadExcelsAPI } from '@/api/modules/system/user';
import { uploadIniAPI, equipmentQueryApi } from '@/api/modules/equipment/equipmentUpload';
import { getDictsApi } from '@/api/modules/system/dictData';
import { download } from '@/api';
import { DataType, userType, getAddUserResult, userQueryType } from '@/type';
import type { UploadProps } from 'antd';
import useStore from '@/store';
import ColorBtn from '@/components/ColorBtn';
import { Key } from 'rc-tree/lib/interface';
import dayjs from 'dayjs';
import { IdictType } from '@/type/modules/system/sysDictData';
import { hasPermi } from '@/utils/auth';
import { useNavigate } from 'react-router-dom';

const { RangePicker } = DatePicker;
const { Dragger } = Upload;

const dataList: { key: React.Key; title: string }[] = [];

const User = () => {
  const [queryForm] = Form.useForm();
  const [resetForm] = Form.useForm();
  const { Search } = Input;
  const {
    useUserStore: { userInfo },
  } = useStore();
  const navigate = useNavigate();

  // 分页
  const [queryParams, setQueryParams] = useState<userQueryType>({ pageNum: 1, pageSize: 10 });
  // 用户列表数据
  const [userList, setUserList] = useState({ count: 0, rows: [] as userType[] });
  const { confirm } = Modal;
  // table loading
  const [loading, setLoading] = useState(true);
  // 更改用户密码
  const [changePwdModalOpen, setChangePwdModalOpen] = useState(false);
  // 保存 当前选择用户信息
  const [currentUser, setCurrentUser] = useState<userType>({});
  // 新增编辑 model显隐
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 显隐列 model显隐
  const [showHiddenOpen, setShowHiddenOpen] = useState(false);
  const [targetKeys, setTargetKeys] = useState<string[]>([]);
  // add user btn
  const [postRole, setPostRole] = useState<getAddUserResult>({ posts: [], roles: [] });
  const [propsValues, setPropsValues] = useState<userType>({
    status: '0',
    sex: '2',
    password: '',
  });
  // 非单个禁用
  const [single, setSingle] = useState(true);
  // 非多个禁用
  const [multiple, setMultiple] = useState(true);
  // 控制搜索隐藏显示
  const [searchShow, setSearchShow] = useState(true);
  // 保存table 选择的key
  const [selectKeys, setSelectKeys] = useState<React.Key[]>([]);
  // 保存table 选择的key
  const [rowKeys, setRowKeys] = useState('');
  // left deptTree
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [searchValue, setSearchValue] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  // 树状数据
  const [defaultData, setDefaultData] = useState<DataNode[]>([]);
  // 文件上传
  const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);
  // 文件上传 判断是否更新用户数据
  const [isUpdateSupport, setIsUpdateSupport] = useState('0');
  // 存储已上传的文件
  const [isFiles, setIsFiles] = useState<UploadFile<any>[]>([]);
  // dicts
  const [dictStatus, setDictStatus] = useState<IdictType[]>([]);
  const [dictSex, setDictSex] = useState<IdictType[]>([]);

  // 初始化获取字典
  const getDicts = async () => {
    try {
      const status = await getDictsApi('sys_normal_disable');
      setDictStatus(status.data.result);
      const sexs = await getDictsApi('sys_user_sex');
      setDictSex(sexs.data.result);
    } catch (error) {}
  };

  // 查询列表
  const getList = async () => {
    try {
      const { data } = await getUserListAPI(queryParams);

      setUserList({ ...data.result });
      setLoading(false);
    } catch (error) {}
  };
  useEffect(() => {
    getList();
  }, [queryParams]);

  const searchQueryFn = () => {
    // eslint-disable-next-line prefer-const
    let { createdAt, ...form } = queryForm.getFieldsValue();
    if (createdAt) {
      form = {
        ...form,
        beginTime: dayjs(createdAt[0]).format('YYYY-MM-DD HH:mm:ss'),
        endTime: dayjs(createdAt[1]).format('YYYY-MM-DD HH:mm:ss'),
      };
    }
    setQueryParams({
      pageNum: 1,
      pageSize: 10,
      ...form,
    });
  };

  const resetQueryFn = () => {
    queryForm.resetFields();
    setSelectKeys([]);
    setQueryParams({ pageNum: 1, pageSize: 10 });
  };

  // excel 导入
  const props: UploadProps = {
    name: 'file',
    multiple: true,
    accept: '.ini',
    fileList: isFiles,
    beforeUpload: () => false,
    onChange: (info) => {
      setIsFiles(info.fileList);
    },
  };
  const handleUploadOk = async () => {
    try {
      const fd = new FormData();
      fd.append('updateSupport', isUpdateSupport);
      isFiles.forEach((file: any) => {
        fd.append('iniFiles', file.originFileObj);
      });
      const { data } = await uploadIniAPI(fd);
      message.success(data.message);
      setIsUploadModalOpen(false);
      setIsUpdateSupport('0');
      setIsFiles([]);
    } catch (error) {}
  };
  const equipmentQuery = async () => {
    try {
      const { data } = await equipmentQueryApi();

      message.success(data.message);
      document.querySelector('#contentDIV').innerHTML = JSON.stringify(data.result);
    } catch (error) {}
  };
  const handleUploadCancel = () => {
    setIsUploadModalOpen(false);
    setIsFiles([]);
    setIsUpdateSupport('0');
  };

  // 获取用户数据
  const getUserListFn = async (userId: number | string) => {
    try {
      const { data } = await getUserInfoAPI(userId);
      setPropsValues(data.result);
      setPostRole({
        posts: data.result.posts,
        roles: data.result.roles,
      } as getAddUserResult);
    } catch (error) {}
  };

  return (
    <div className="app-container">
      <Row gutter={16} className="sys-user">
        <Col span={20}>
          <Row gutter={16} className="mb10">
            <Col span={16} className="leno-btn">
              <Row gutter={8}>
                <Col>
                  <ColorBtn
                    hidden={hasPermi('system:user:remove')}
                    color="info"
                    icon={<ToTopOutlined />}
                    onClick={() => {
                      setIsUploadModalOpen(true);
                    }}
                  >
                    导入
                  </ColorBtn>
                  <Button hidden={hasPermi('tool:gen:preview')} onClick={() => equipmentQuery()} size="small" type="link">
                    查询
                  </Button>
                </Col>
              </Row>
            </Col>
            <div id="contentDIV"></div>
          </Row>

          <Modal title="用户导入" open={isUploadModalOpen} onOk={handleUploadOk} onCancel={handleUploadCancel}>
            <Dragger {...props} height={200}>
              <p className="ant-upload-drag-icon">
                <InboxOutlined />
              </p>
              <p className="ant-upload-text">将文件拖到此处，或点击上传</p>
            </Dragger>
            <Row justify="center" align="middle" style={{ fontSize: 12, color: '#808080' }}>
              支持单文件、多文件上传
            </Row>
          </Modal>
        </Col>
      </Row>
    </div>
  );
};

export default User;
